var express = require('express');
const { listen } = require('../app');
var router = express.Router();
var mongo = require("./db");
var mongodb = require("mongodb");
var ObjectId = mongodb.ObjectId;

/* GET home page. */
router.get('/', function (req, res, next) {
  // res.render('index', { title: 'Express' });
});

// 查询接口
router.post("/all", function (req, res) {
  var obj = {}
  if (req.body.se) { //查询条件
    obj.se = req.body.se;
  }
  mongo("find", "userlist", obj, function (data) {
    res.send(data)
  })
})
// 添加接口
router.post("/add", function (req, res) {
  var obj = {
    pid: req.body.pid,
    name: req.body.name,
    price: req.body.price,
    num: 1,
    img: req.body.img
  }
  mongo("find", "cartlist", { pid: req.body.pid }, function (data) {
    if (data.length != 0) {
      var mynum = Number(data[0].num) //找出以前的数量 
      mynum++;
      mongo("update", "cartlist", [{ pid: req.body.pid }, { num: mynum }], function () {
        res.send({ success: "数量更新成功" })
      })
    } else {
      mongo("insert", "cartlist", obj, function () {
        res.send({ success: "添加成功" })
      })
    }
  })
})
// 获取购物车列表的接口
router.post("/cartAll", function (req, res) {
  mongo("find", "cartlist", {}, function (data) {
    res.send(data)
  })
})
// 更新数量接口
router.post("/updateNum", function (req, res) {
  if (req.body.num < 1) {
    mongo("del", "cartlist", { _id: ObjectId(req.body.id) }, function () {
      res.send({ success: "删除成功" })
    })
  } else {
    mongo("update", "cartlist", [{ _id: ObjectId(req.body.id) }, { num: req.body.num }], function () {
      res.send({ success: "修改数量成功" })
    })
  }
})

module.exports = router;
